import { createSlice } from '@reduxjs/toolkit';


export const cartSlice = createSlice({
  name: 'cart',
  initialState: {
    tabs: null,
    tags: null,
    goods: null,
    currentCateId: 1,

    shoppingCart: JSON.parse(localStorage.getItem('shoppingCart')) || [],
  },
  reducers: {
    changeInitData: (state, action) => {
      state.tabs = action.payload.tabs;
      state.tags = action.payload.tags;
      state.goods = action.payload.goods;
    },
    changeCurrentCateId: (state, action) => {
      state.currentCateId = Number(action.payload.sort);
    },
    changeShoppingCart: (state, action) => {
      state.shoppingCart = action.payload;
    },

    // 加入购物车
    addToCart: (state, action) => {
      let tempArr = state.shoppingCart.filter(o => o.cakeId == action.payload.id) || []
      if (tempArr.length !== 0) {
        state.shoppingCart = state.shoppingCart.map(o => {
          if (o.cakeId == action.payload.id) {
            return { ...o, count: o.count + 1, update: Date.now() }
          }
          return o
        })
      } else {
        state.shoppingCart = [{ cakeId: action.payload.id, count: 1, update: Date.now() }, ...state.shoppingCart]
      }
    },

    // 清空购物车
    clsShoppingCart: (state) => {
      state.shoppingCart = []
    },

    // 购物车商品数量增加
    increase: (state, action) => {
      state.shoppingCart = state.shoppingCart.map(o => {
        if (o.cakeId == action.payload.id) {
          return { ...o, count: o.count + 1 }
        }
        return o
      })
    },

    // 购物车商品数量减少
    decrease: (state, action) => {
      state.shoppingCart = state.shoppingCart.map(o => {
        if (o.cakeId == action.payload.id) {
          return { ...o, count: o.count - 1 }
        }
        return o
      })
    },

    // 购车删除商品
    delCartGoods: (state, action) => {
      state.shoppingCart = state.shoppingCart.filter(o => o.cakeId != action.payload.id)
    },
  }
});

export const {
  changeInitData,
  changeCurrentCateId,
  changeShoppingCart,
  addToCart,
  clsShoppingCart,
  increase,
  decrease,
  delCartGoods,
} = cartSlice.actions;

export const selectTabs = (state) => state.cart.tabs;
export const selectTags = (state) => state.cart.tags;
export const selectGoods = (state) => state.cart.goods;
export const selectCurrentCateId = (state) => state.cart.currentCateId;
export const selectShoppingCart = (state) => state.cart.shoppingCart;

export default cartSlice.reducer;
